package cn.jhz.learn.community_dynamic.manager;

import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.springframework.stereotype.Service;

import cn.jhz.learn.community_dynamic.dao.LoginIdJpaRepository;
import cn.jhz.learn.community_dynamic.model.LoginIdEntity;

@Service
public class LoginIdManager {
    private final LoginIdJpaRepository loginIdJpaRepository;
     
    public LoginIdManager(LoginIdJpaRepository loginIdJpaRepository) {
	super();
	this.loginIdJpaRepository = loginIdJpaRepository;
    }

    public List<LoginIdEntity> batchCreateInstantces(Long times) {
	Set<Long> idSet =  loginIdJpaRepository.findAll().parallelStream().map(LoginIdEntity::getId).collect(Collectors.toCollection(ConcurrentSkipListSet::new));
	
	UUID.randomUUID().getMostSignificantBits();
	Random random = new Random();
	Double len = Math.pow(10, 9 - 1);
	
	return Stream.generate(random::nextDouble).parallel().map(val -> (long) ((val * 9 + 1) * len)).filter(val->!idSet.contains(val)).limit(times).collect(Collectors.toSet()).parallelStream().map(LoginIdEntity::new).collect(Collectors.toList());
    }
    
    public synchronized LoginIdEntity getEntity() {
	LoginIdEntity entity = this.loginIdJpaRepository.findFirstByStatus((byte)0);
	entity.setStatus((byte)1);
	this.loginIdJpaRepository.saveAndFlush(entity);
	return entity;
    }
}
